package com.alibaba.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.yygh.cmn.listener.DictListener;
import com.alibaba.yygh.cmn.mapper.DictMapper;
import com.alibaba.yygh.cmn.service.DictService;
import com.alibaba.yygh.common.exception.YyghException;
import com.alibaba.yygh.model.cmn.Dict;
import com.alibaba.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * description: DictServiceImpl
 * @author: gql
 * @date: 2021/11
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    /**
     * 1.根据数据id查询子数据列表
     * @param id
     * @return
     */
    // Cacheable:对返回结果进行缓存
    @Cacheable(value = "dict")
    @Override
    public List<Dict> findChlidData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            boolean flag = this.isChildren(dictId);
            dict.setHasChildren(flag);
        }
        return dictList;
    }

    /**
     * 1.2判断id下面是否有子节点
     * @param id
     * @return
     */
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(wrapper);
        return count > 0;
    }

    /**
     * 2.导出Excel
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            // 1.设置下载头和其他信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码,和 Easyexcel 没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 2.把数据字典表所有数据查询出来
            List<Dict> dictList = baseMapper.selectList(null);
            List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
            for (Dict dict : dictList) {
                DictEeVo dictVo = new DictEeVo();
                // 把List<Dict>  --->  List<DictEeVo>
                BeanUtils.copyProperties(dict, dictVo);
                dictVoList.add(dictVo);
            }
            // 3.写出到Excel中
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("数据字典")
                    .doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Autowired
    private DictListener dictListener;

    /**
     * 3.导入Excel
     * @param file
     */
    @Override
    public void importDictData(MultipartFile file) {
        try {
            /**
             * read(args1,args2,args3):输入流、实体类class、监听器
             */
            EasyExcel.read(file.getInputStream(), DictEeVo.class, dictListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 4.根据dictCode与value获取数据字典名称
     * @param dictCode
     * @param value
     * @return
     */
    @Override
    public String getNameByDictCodeAndValue(String dictCode, String value) {
        // 如果dictCode为空，则根据value也能唯一定位数据字典 例如：省市区的value值能够唯一确定
        if (StringUtils.isEmpty(dictCode)) {
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value", value);
            Dict dict = baseMapper.selectOne(wrapper);
            if (null == dict) {
                throw new YyghException(20001, "数据不存在");
            }
            // 返回数据字典名称
            return dict.getName();
        } else {
            // 1. 根据dict_code值查询上层数据
            Dict parentDict = this.getDictByDictCode(dictCode);

            // 2.根据parent_id和value查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id", parentDict.getId()).eq("value", value);
            Dict dict = baseMapper.selectOne(wrapper);
            if (null == dict) {
                throw new YyghException(20001, "数据不存在");
            }
            // 返回数据字典名称
            return dict.getName();
        }
    }

    /**
     * 根据dictCode查询下级节点数据
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        // 1. 根据dict_code值查询parent_id
        Dict parentDict = this.getDictByDictCode(dictCode);

        // 2. 根据parent_id查询
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",parentDict.getId());
        List<Dict> dictList = baseMapper.selectList(wrapper);

        return dictList;
    }

    /**
     * 根据dictCode查询数据字典
     * @param dictCode
     * @return
     */
    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        Dict parentDict = baseMapper.selectOne(wrapper);
        if (null == parentDict) {
            throw new YyghException(20001, "数据不存在");
        }
        return parentDict;
    }

}
